package com.lvmama.config;

import java.util.LinkedHashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Author:xuzhongwei
 * @Description:
 * @Date：2018/08/06
 */
@Configuration
public class RedisClusterConfig {


    @Value("${spring.redis.hosts}")
    private String hosts;

    @Value("${spring.redis.maxtotal}")
    private Integer maxtotal;

    @Value("${spring.redis.maxidle}")
    private Integer maxidle;

    @Value("${spring.redis.maxwaitmillis}")
    private Integer maxwaitmillis;

    @Bean
    public JedisCluster jedisCluster() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 最大连接数
        poolConfig.setMaxTotal(maxtotal);
        // 最大空闲数
        poolConfig.setMaxIdle(maxidle);
        // 最大允许等待时间，如果超过这个时间还未获取到连接，则会报JedisException异常：
        poolConfig.setMaxWaitMillis(maxwaitmillis);
        Set<HostAndPort> nodes = new LinkedHashSet<>();
        if (hosts != null)
            for (String str : hosts.split(","))
                nodes.add(new HostAndPort(str.split(":")[0], Integer.parseInt(str.split(":")[1])));
        return new JedisCluster(nodes, poolConfig);
    }
}
